package com.gitee.feizns.explore.data_structure.string;

/**
 * 58. 最后一个单词的长度
 * @author feizns
 * @since 2020/1/16
 */
public class LengthOfLastWord {

    public static void main(String[] args) {
        System.out.println(lengthOfLastWord(" "));
    }

    public static int lengthOfLastWord(String s) {
        if ( s == null || s.isEmpty() || isBlank(s) )
            return 0;

        int start;
        int end = s.length() - 1;
        for (start = s.length() - 2; start >= 0; start--) {
            if ( s.charAt(start) == ' ' && s.charAt(start + 1) != ' ' )
                break;
            if ( s.charAt(end) == ' ' )
                end--;
        }
        return end - start;
    }

    private static boolean isBlank(String s) {
        for (int i = 0; i < s.length(); i++) {
            if ( s.charAt(i) != ' ' )
                return false;
        }
        return true;
    }

}
